<?php
/**
 * SOCKET基础服务类
 *
 * @packaged default
 * @author slash
 **/
class stocketService
{
    var $header_len = 4;

	function stocket_connet($host,$port,$secend=1)
	{
		$createSocket = socket_create( AF_INET, SOCK_STREAM, SOL_TCP );
		if($createSocket==false){
			$this->socket = false;
			return false;
		}
        //设置连接超时 1s
        if($secend){
		    @socket_set_option($this->socket,SOL_SOCKET,SO_RCVTIMEO,array("sec"=>$secend, "usec"=>0 ) );
		//设置接收超时 1s
		    @socket_set_option($this->socket,SOL_SOCKET,SO_SNDTIMEO,array("sec"=>$secend, "usec"=>0 ) );
        }
        if(socket_connect( $this->socket, $host, $port )){
			$this->socket = $createSocket;
			return true;
		}else{
			$this->socket = false;
			return false;
		}
	}
	function bulid($cmd,$send_list)
	{
		if($this->socket == false){
			return false;
		}
		$send_contents = json_encode($send_list);
		$send_len = strlen($send_contents);
		$temp = pack("nna{$send_len}",$cmd,$send_len,$send_contents);
		socket_write($this->socket,$temp,strlen($temp));
	}
	function paser()
	{
		/*
		if(!is_object($this->socket))
		{
			return array('cmd'=>0,'body_len'=>0,'content'=>'');
		}
		*/
		socket_recv( $this->socket,$buf, $this->header_len,0);
		if($buf==''){
			return array('cmd'=>0,'body_len'=>0,'content'=>'');
		}
		$temp = unpack('ncmd/nlen', $buf );
		//print_r($temp);exit();
		$cmd = $temp['cmd'];
		$body_len = $temp['len'];
		$recv="";
		while(strlen($recv)<$body_len)
		{
			$get_len = $body_len-strlen($recv);
			$buf = "";
			socket_recv( $this->socket,$buf,$get_len,0);
			$recv .=$buf;
		}
		$body_contnet = "";
		if($body_len>0)
		{
			$temp = unpack("a{$body_len}",$recv);
			$body_contnet = json_decode($temp[1]);
		}
		$temp_arr = array('cmd'=>$cmd,'body_len'=>$body_len,'content'=>$body_contnet);
		return $temp_arr;
	}
	function close()
	{
		socket_close($this->socket);
	}
}

?>
